//
//  JYTSearchSchoolViewController.m
//  JYT_IOS
//
//  Created by nxa-tankeke on 17/1/4.
//  Copyright © 2017年 nxa-yuanguoxiang. All rights reserved.
//

#import "JYTSearchSchoolViewController.h"
#import "JYTSchoolManager.h"
#import "JYTSearchRecordCell.h"
#import "JYTCityZoneView.h"
#import "JYTSchoolTableViewCell.h"
#import <MJRefresh.h>
#import "JYTSchoolHandler.h"

@interface JYTSearchSchoolViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong)UIButton *leftBtn;
@property (nonatomic, strong)UIButton *rightBtn;
@property (nonatomic, strong)UIButton *zonetBtn;
@property (nonatomic, strong) UITextField * searchText;
@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) UITableView *schoolTableView;
@property (nonatomic,strong)NSMutableArray * searchHistory;
@property (nonatomic,strong)NSArray *myArray;
@property (nonatomic, strong)NSMutableArray * schools;
@property (nonatomic, strong)JYTCity *currentCity;
@property (nonatomic, strong)JYTZone *currentZone;

@property (nonatomic, strong)NSDictionary * parms;

@property (nonatomic, assign)NSInteger page;
@end

@implementation JYTSearchSchoolViewController
-(NSMutableArray *)schools
{
    if (_schools == nil) {
        _schools = [NSMutableArray array];
    }
    
    return _schools;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:NO];
    
    self.myTableView.hidden = NO;
    
    [self readNSUserDefaults];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    BOOL isUsedOffLine = [[JYTUserManager shared] isUsedOffLine];
    if (!isUsedOffLine) {
        
        User *user = [[JYTUserManager shared] getUser];
        _currentCity = [[JYTUserManager shared] getCityById:user.cityId];
        
    }else {
        _currentCity =[[[JYTUserManager shared] getCityArr] firstObject];
        
    }
    JYTZone * first = [[JYTZone alloc]init];
    first.zone_id = _currentCity.zone_id;
    first.zone_name = _currentCity.zone_name;
    first.parent_id = _currentCity.parent_id;
    first.service_url = _currentCity.service_url;
    first.weixin_url = _currentCity.weixin_url;
    _currentZone = first;
    
    UIView *nav = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CURRENT_SCREEN_WIDTH, 64)];
    nav.backgroundColor = [UIColor colorWithRed:131/255.0f green:182/255.0f blue:248/255.0f alpha:1];
    [self.view addSubview:nav];
    
    _leftBtn = [[UIButton alloc] init];
    [nav addSubview:_leftBtn];
    [_leftBtn.titleLabel setFont:[UIFont systemFontOfSize:12]];
    //        [leftBtn setHidden:YES];
    [_leftBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_leftBtn addTarget:self action:@selector(clickLeftButton) forControlEvents:UIControlEventTouchUpInside];
    [_leftBtn setBackgroundImage:[UIImage imageNamed:@"ic_goback"] forState:UIControlStateNormal];
    [_leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(nav.mas_top).with.offset(22);
        make.left.equalTo(nav.mas_left).with.offset(15);
        make.width.mas_equalTo(24);
        make.bottom.equalTo(nav.mas_bottom).with.offset(-2);
    }];
    
    _rightBtn = [[UIButton alloc] init];
    [nav addSubview:_rightBtn];
    [_rightBtn.titleLabel setFont:[UIFont systemFontOfSize:17]];
    [_rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_rightBtn setTitle:@"搜索" forState:UIControlStateNormal];
    [_rightBtn addTarget:self action:@selector(clickRightButton) forControlEvents:UIControlEventTouchUpInside];
    [_rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(nav.mas_top).with.offset(22);
        make.right.equalTo(nav.mas_right).with.offset(-15);
        make.width.mas_equalTo(38);
        make.bottom.equalTo(nav.mas_bottom).with.offset(-2);
    }];
    
    UIView *midel = [[UIView alloc]init];
    midel.backgroundColor = [UIColor clearColor];
    [nav addSubview:midel];
    [midel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(nav.mas_top).with.offset(22);
        make.right.equalTo(_rightBtn.mas_left).with.offset(-5);
        make.left.equalTo(_leftBtn.mas_right).with.offset(5);
    
        make.bottom.equalTo(nav.mas_bottom).with.offset(-2);
    }];
    
    _zonetBtn = [[UIButton alloc]init];
    [midel addSubview:_zonetBtn];
    [_zonetBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [_zonetBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    //[_zonetBtn setTitle:@"新乡市" forState:UIControlStateNormal];
    [_zonetBtn setTitle:_currentCity.zone_name forState:UIControlStateNormal];
    [_zonetBtn addTarget:self action:@selector(clickZoneButton) forControlEvents:UIControlEventTouchUpInside];
    [_zonetBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(midel.mas_top).with.offset(-2);
        make.left.equalTo(midel.mas_left).with.offset(2);
        make.width.mas_equalTo(65);
       make.bottom.equalTo(midel.mas_bottom).with.offset(0);
    }];
    
    _searchText = [[UITextField alloc]init];
    [midel addSubview:_searchText];
    [_searchText setPlaceholder:@"输入驾校名称"];
    [_searchText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(midel.mas_top).with.offset(0);
        make.left.equalTo(_zonetBtn.mas_right).with.offset(5);
        make.right.equalTo(midel.mas_right).with.offset(2);
        make.bottom.equalTo(midel.mas_bottom).with.offset(0);
    }];
    
    _searchHistory = [NSMutableArray array];
    
    _schoolTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, CURRENT_SCREEN_WIDTH, CURRENT_SCREEN_HEIGHT - 64) style:UITableViewStylePlain];
    _schoolTableView.delegate = self;
    _schoolTableView.dataSource = self;
    [self.view addSubview:_schoolTableView];
     [_schoolTableView registerNib:[UINib nibWithNibName:NSStringFromClass([JYTSchoolTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"school"];
    _schoolTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.schoolTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    _myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, CURRENT_SCREEN_WIDTH, CURRENT_SCREEN_HEIGHT - 64) style:UITableViewStylePlain];
    _myTableView.delegate = self;
    _myTableView.dataSource = self;
    [self.view addSubview:_myTableView];
    [_myTableView registerClass:[JYTSearchRecordCell class] forCellReuseIdentifier:@"KsearchRecordCellId"];
    self.myTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
}

- (void)clickZoneButton
{
    JYTCityZoneView *cz = [[JYTCityZoneView alloc]initWithFrame:CGRectMake(0, 64, CURRENT_SCREEN_WIDTH, 280)];
    [cz setSelect:^(NSInteger index, JYTZone *zone) {
        //MyLog(@"---------%@",zone.zone_name);
        _currentZone = zone;
        [self.zonetBtn setTitle:zone.zone_name forState:UIControlStateNormal];
        
 
    }];
    [cz show];
}

- (void)clickLeftButton
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)clickRightButton
{
    if (_searchText.text.length > 0) {

        [JYTSchoolManager SearchText:_searchText.text];
        [self readNSUserDefaults];
        self.myTableView.hidden = YES;
        
        [self.schools removeAllObjects];
        [self.schoolTableView reloadData];
        [self setupRefresh];
        
    }else{
        [self showMessage:@"输入驾校名称"];
        
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.myTableView) {
        if (_myArray.count>0) {
            return _myArray.count+1+1;
        }else{
            return 1;
        }
    } else {
         return self.schools.count;
    }

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.myTableView) {
        if(indexPath.row == 0){
            UITableViewCell * cell = [[UITableViewCell alloc] initWithStyle:0 reuseIdentifier:@"cell"];
            cell.textLabel.text = @"历史搜索";
            cell.textLabel.textColor = [UIColor lightGrayColor];
            [cell.imageView setImage:[UIImage imageNamed:@"motify"]];
            
            return cell;
        }else if (indexPath.row == _myArray.count+1){
            UITableViewCell * cell = [[UITableViewCell alloc] initWithStyle:0 reuseIdentifier:@"cell"];
            cell.textLabel.text = @"清除历史记录";
            cell.textLabel.textColor = [UIColor lightGrayColor];
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            return cell;
        }else{
            JYTSearchRecordCell * cell = [tableView dequeueReusableCellWithIdentifier:@"KsearchRecordCellId"];
            NSArray* reversedArray = [[_myArray reverseObjectEnumerator] allObjects];
            cell.lableText.text = reversedArray[indexPath.row-1];
            cell.lableText.textColor = [UIColor blackColor];
            //            if (self.myArray.count != 0 ) {
            //                 cell.lableText.text = self.myArray[self.myArray.count-1-indexPath.row];
            //            }
            return cell;
        }

    } else {
        
        JYTSchoolTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"school"];
        cell.school = self.schools[indexPath.row];
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.myTableView) {
        if (indexPath.row == _myArray.count+1) {
            return 70;
        }
        self.myTableView.estimatedRowHeight = 44.0f;
        //    self.searchTableView.estimatedRowHeight = 44.0f;
        return UITableViewAutomaticDimension;

    } else {
         return 130;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.myTableView) {
        if (indexPath.row == _myArray.count+1) {//清除所有历史记录
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"清除历史记录" message:@"" preferredStyle: UIAlertControllerStyleAlert];
            
            //@“ UIAlertControllerStyleAlert，改成这个就是中间弹出" UIAlertControllerStyleActionSheet
            
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [JYTSchoolManager removeAllArray];
                _myArray = nil;
                [self.myTableView reloadData];
                
            }];
            [alertController addAction:cancelAction];
            [alertController addAction:deleteAction];
            //            [alertController addAction:archiveAction];
            [self presentViewController:alertController animated:YES completion:nil];
        }else{
            
        }
        
        if (indexPath.row == 0) {
            return;
        }

    } else {
        
        
    }
    
    
    
}

-(void)readNSUserDefaults{//取出缓存的数据
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    //读取数组NSArray类型的数据
    NSArray * myArray = [userDefaultes arrayForKey:@"myArray"];
    self.myArray = myArray;
    [self.myTableView reloadData];
    //NSLog(@"myArray======%@",myArray);
    
}

- (void)showMessage:(NSString *)message
{
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    UIView *showview =  [[UIView alloc]init];
    showview.backgroundColor = [UIColor blackColor];
    showview.frame = CGRectMake(1, 1, 1, 1);
    showview.alpha = 1.0f;
    showview.layer.cornerRadius = 5.0f;
    showview.layer.masksToBounds = YES;
    [window addSubview:showview];
    
    UILabel *label = [[UILabel alloc]init];
    label.text = message;
    
    //    CGSize LabelSize = [message sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(290, 9000)];
    //初始化段落，设置段落风格
    
    NSMutableParagraphStyle *paragraphstyle=[[NSMutableParagraphStyle alloc]init];
    paragraphstyle.lineBreakMode=NSLineBreakByCharWrapping;
    
    //设置label的字体和段落风格
    
    NSDictionary *dic=@{NSFontAttributeName:label.font,NSParagraphStyleAttributeName:paragraphstyle.copy};
    
    //计算label的真正大小,其中宽度和高度是由段落字数的多少来确定的，返回实际label的大小
    
    CGRect rect=[label.text boundingRectWithSize:CGSizeMake(290, 9000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    CGSize LabelSize = CGSizeMake(rect.size.width, rect.size.height);
    label.frame = CGRectMake(10, 5, LabelSize.width, LabelSize.height);
    label.textColor = [UIColor whiteColor];
    label.textAlignment = 1;
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:15];
    [showview addSubview:label];
    showview.frame = CGRectMake((CURRENT_SCREEN_WIDTH - LabelSize.width - 20)/2, CURRENT_SCREEN_HEIGHT - 100, LabelSize.width+20, LabelSize.height+10);
    [UIView animateWithDuration:2 animations:^{
        showview.alpha = 0;
    } completion:^(BOOL finished) {
        [showview removeFromSuperview];
    }];
}

- (void)setupRefresh
{
    self.schoolTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreS)];
    
    self.schoolTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewS)];
    
    self.schoolTableView.mj_header.automaticallyChangeAlpha = YES;
    
    [self.schoolTableView.mj_header beginRefreshing];
    
    
}

- (void)loadNewS
{
    [self.schoolTableView.mj_footer endRefreshing];
    
    NSMutableDictionary *parms = [NSMutableDictionary dictionary];
    
    [parms setObject:_currentZone.zone_id forKey:@"ZoneId"];
    [parms setObject:_searchText.text forKey:@"DrivingName"];
    [parms setObject:@"0" forKey:@"PageNo"];
    [parms setObject:@"10" forKey:@"PageSize"];
    
    self.parms = parms;
    
    [[JYTSchoolHandler shared] getSchoolWithParam:parms WithHandler:^(NSArray *coaches, NSString *pageNo) {
        if (self.parms != parms) {
            return ;
        }
        
        if (coaches.count > 0) {
            
            [self.schools removeAllObjects];
            
            [self.schools addObjectsFromArray:coaches];
            
            [self.schoolTableView reloadData];
            
            [self.schoolTableView.mj_header endRefreshing];
            
            self.page = 0;
            
        } else {
            if (self.parms != parms) {
                return ;
            }
            
            [self.schoolTableView.mj_header endRefreshing];
        }
    }];
}


- (void)loadMoreS
{
    [self.schoolTableView.mj_header endRefreshing];
    
    NSInteger page = self.page + 1;
    NSString *pageStr = [NSString stringWithFormat:@"%ld", page];
    
    NSMutableDictionary *parms = [NSMutableDictionary dictionary];
    
    [parms setObject:_currentZone.zone_id forKey:@"ZoneId"];
    
    [parms setObject:_searchText.text forKey:@"DrivingName"];
    [parms setObject:pageStr forKey:@"PageNo"];
    [parms setObject:@"10" forKey:@"PageSize"];
    self.parms = parms;
    
    [[JYTSchoolHandler shared] getSchoolWithParam:parms WithHandler:^(NSArray *coaches, NSString *pageNo) {
        if (self.parms != parms) {
            return ;
        }
        
        if (coaches.count > 0) {
            
            [self.schools addObjectsFromArray:coaches];
            
            [self.schoolTableView reloadData];
            
            [self.schoolTableView.mj_footer endRefreshing];
            
            self.page = page;
        } else {
            if (self.parms != parms) {
                return ;
            }
            
            [self.schoolTableView.mj_footer endRefreshing];
        }
        
    }];
    
}


@end
